package rad.framework.mail;

import java.util.List;

import rad.framework.trace.Trace;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.Renderer;
import org.jboss.seam.log.Log;

/**
 * Simple mail sender.
 * 
 * @author boudyacho
 * 
 */
@Name("simpleMailSender")
@Trace
public class Mailer {

	@Logger
	private Log log;

	/**
	 * Setup context and send.
	 */
	public void send(String viewId, String subject, Object from, List to) {
		if (to.size() > 0) {
			Contexts.getEventContext().set("subject", subject);
			Contexts.getEventContext().set("from", from);
			Contexts.getEventContext().set("to", to);

			Renderer.instance().render(viewId);
		} else {
			log.warn("No email addresses for subject: " + subject);
		}
	}

	/**
	 * Assumes subject and from are setup in the template.
	 */
	public void send(String viewId, List to) {
		if (to.size() > 0) {
			Contexts.getEventContext().set("to", to);

			Renderer.instance().render(viewId);
		} else {
			log.warn("No email addresses for subject: " + viewId);
		}
	}

	/**
	 * Simple mail template with body as simple string.
	 */
	public void send(String subject, Object from, List to, String body) {
		if (to.size() > 0) {
			Contexts.getEventContext().set("body", body);
		}
		send("/simple-mail.xhtml", subject, from, to);
	}

	
	/**
	 * Simple container for name and email address. Optional.
	 */
	public static class Person {
		private String name;
		private String email;

		public Person(String name, String email) {
			this.name = name;
			this.email = email;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getEmail() {
			return email;
		}

		public void setEmail(String email) {
			this.email = email;
		}

		@Override
		public String toString() {
			return ToStringBuilder.reflectionToString(this,
					ToStringStyle.MULTI_LINE_STYLE);
		}		
	}
}
